<?php
/*
 * Created on 2007/01/22
 *
 * To change the template for this generated file go to
 * Window - Preferences - PHPeclipse - PHP - Code Templates
 */
class CsvComponent extends Object{
	function createCSV($file_name,$col_name,$values,$col_key=false,$info_from_list=null,$separate=',',$encoding='GB2312'){
		ob_start(); 
		define("FILETYPE","csv");
		
		header("Content-type:application/vnd.ms-excel "); 
		if(FILETYPE=="xls") 
		header("Content-Disposition:filename=$file_name.xls"); 
		else 
		header("Content-Disposition:filename=$file_name.csv"); 		
	
		$out = '';
		$out_line = '';
		if($col_key){
			foreach($col_name as $key=>$val){
				$col_orders[]= split("/",$key);
				$out_line .= "\"".str_replace('@"@','\"\"',$val)."\"$separate";
			}
			$out_line = substr($out_line,0,strlen($out_line)-strlen($separate));
			$out .= $out_line."\n";	
			foreach($values as $value){
				$out_line = '';
				foreach($col_orders as $c){
					$print_data= isset($value[$c['0']][$c['1']])? $value[$c['0']][$c['1']] : ' ';
					$out_line .= "\"".str_replace('@"@','\"\"',$print_data)."\"$separate";
				}
				$out_line = substr($out_line,0,strlen($out_line)-strlen($separate));				
				$out .= $out_line."\n";				
			}		
		}else{
			foreach($col_name as $col){
				$out_line .= "\"".str_replace('@"@','\"\"',$col)."\"$separate";	
			}
			$out_line = substr($out_line,0,strlen($out_line)-strlen($separate));
			$out .= $out_line."\n";		
			foreach($values as $value){
				$out_line = '';
				foreach($value as $key=>$val){
					$out .= "\"".str_replace('@"@','\"\"',$this->printData($val))."\"$separate";
				}
				$out_line = substr($out_line,0,strlen($out_line)-strlen($separate));
				$out .= $out_line."\n";	
			}				
		}
		$__lang = mb_language();
		$__enc = mb_internal_encoding();
   		mb_internal_encoding( mb_detect_encoding($out) );
   		
		$out = mb_convert_encoding($out, $encoding, "AUTO");

		mb_internal_encoding( $__enc );
   		mb_language($__lang); 				
		echo $out;
	}
	
	function printData($val){
		$result = null;
		if(is_array($val)){
			foreach($val as $k=>$v){
				$this->printData($v);
			}
		}
		else{
			if(!empty($val)){
				$result = $val;
			}
			else{
				$result = " ";
			}
		}
		
		return $result;
	}
}
?>
